package com.carefree.system.common.utils;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.carefree.common.constant.UserConstant;
import com.carefree.common.utils.JwtUtils;
import com.carefree.system.modules.security.entity.RedisUserDetails;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @ClassName:SecurityUtils
 * @Description:
 * @Author Tengbin tengbin234@163.com
 */
@Component
public class SecurityUtils {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public Long getPrincipalForUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String userName = (String) authentication.getPrincipal();
        RedisUserDetails redisUserDetails = JSONObject.parseObject(stringRedisTemplate.opsForValue().get(UserConstant.AUTH_USER_PREFIX + userName), new TypeReference<RedisUserDetails>() {
        });

        return JwtUtils.parseTokenGetUserId(redisUserDetails.getToken());
    }

    public String getPrincipalForUserName() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return (String) authentication.getPrincipal();
    }


}
